<script setup lang="tsx">
import { PropType, ref } from 'vue'
import { CurdData, FieldEnum, SchemaConfig } from '@/api/customer/types'
import { getFieldEnumApi } from '@/api/customer'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { SelectOption } from '@/api/global/types'
import { useI18n } from '@/hooks/web/useI18n'
import { useEnumeratePicker } from '@/utils'
const { t } = useI18n()

// 使用 ref 声明响应式变量 isExpanded
const isExpanded = ref(true)

// 切换展开/收起状态的方法
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})
const { query } = useRoute()

const isLoading = ref(true) // 设置加载状态
let customerFieldEnum: FieldEnum = {}
let operatorOptions: SelectOption[] = []

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }) => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}

// const allSchemas = ref<AllSchemas>({
//   formSchema: [] // 确保与接口匹配
// })

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

const statusOption = ref<Option[]>([]) // 明确指定类型 Option[]
const stageOption = ref<Option[]>([])
const custypeOption = ref<Option[]>([])
const cusnatureOption = ref<Option[]>([])
const sourceOption = ref<Option[]>([])
const isLoginOption = ref<Option[]>([])
const loginStatusOption = ref<Option[]>([])
const isAdvanceOption = ref<Option[]>([])

// 根据枚举值生成选项
const loadOptions = () => {
  statusOption.value = createOptions(customerFieldEnum?.status || {})
  stageOption.value = createOptions(customerFieldEnum?.stage || {})
  custypeOption.value = createOptions(customerFieldEnum?.custype || {})
  cusnatureOption.value = createOptions(customerFieldEnum?.cusnature || {})
  sourceOption.value = createOptions(customerFieldEnum?.source || {})
  isLoginOption.value = createOptions(customerFieldEnum?.is_login || {})
  loginStatusOption.value = createOptions(customerFieldEnum?.login_status || {})
  isAdvanceOption.value = createOptions(customerFieldEnum?.is_advance || {})
}

const fetchData = async () => {
  await getFieldEnumApi({ field: 'all' }).then((res) => {
    customerFieldEnum = res.data
  })
  await getOperatorSelectListApi({}).then((res) => {
    operatorOptions = res.data.list
  })

  // const schemaConfig: any = {
  //   fieldEnum: customerFieldEnum,
  //   operatorOptions,
  //   fromPage: query.source === '/public-page' ? 'public' : ''
  // }
  // const { crudSchemas } = useSchema(schemaConfig)
  // const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

  // 合并新的数据，确保不改变原有数据的类型
  // allSchemas.value = {
  //   detailSchema: newSchemas.detailSchema || []
  // }

  // 初始化附件列表
  attachList.value = (props.currentRow?.att_path_urls || []).map((item: any) => ({
    id: item.id || 0,
    url: item.url || '',
    name: item.name || item.url?.split('/').pop() || '未知文件'
  }))

  isLoading.value = false // 数据加载完成后更新状态
  // 数据加载完成后，调用 loadOptions 函数
  loadOptions()
}

fetchData()

// 格式化合作伙伴字符串
const formatPartnerStr = (partnerIds) => {
  if (!partnerIds) {
    return ''
  }
  return partnerIds
    .map((id) => operatorOptions.find((item) => item.value === id)?.label || '')
    .join(' ')
}

// 文件相关的响应式变量
type imageType = {
  id: number
  url: string
  name: string
}
let attachList = ref<imageType[]>([])
const previewVisible = ref(false)
const previewTitle = ref('')
const previewType = ref('')
const dialogFile = ref<imageType>({
  id: 0,
  url: '',
  name: ''
})

const fileExtensions = {
  image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
  pdf: ['.pdf'],
  text: ['.txt', '.html', '.md']
}

// 判断文件是否可以预览
const isPreviewable = (fileUrl: string) => {
  const extension = fileUrl.slice(fileUrl.lastIndexOf('.')).toLowerCase()

  if (fileExtensions.image.includes(extension)) {
    return 'image'
  }
  if (fileExtensions.pdf.includes(extension)) {
    return 'pdf'
  }
  if (fileExtensions.text.includes(extension)) {
    return 'text'
  }
  return 'other' // 无法预览的文件类型
}

// 文件点击事件处理
const handleFileClick = (fileParams) => {
  const type = isPreviewable(fileParams.url)
  console.log(type)
  if (type === 'other') {
    // 如果文件不可预览，直接下载
    handleFileDownload(fileParams)
  } else {
    // 如果文件可预览，弹出预览框
    previewType.value = type
    previewTitle.value = fileParams.name
    previewVisible.value = true
    dialogFile.value.url = fileParams.url
  }
}

const handleFileDownload = async (fileParams) => {
  try {
    // 如果是图片文件，打开新标签页
    if (fileParams.url && fileParams.url.match(/\.(jpg|jpeg|png|gif|bmp)$/i)) {
      // 在新标签页中打开图片
      window.open(fileParams.url, '_blank')
    } else {
      // 对于其他文件类型，直接使用文件 URL进行下载
      const link = document.createElement('a')
      link.download = fileParams.name || 'download' // 设置文件名
      link.href = fileParams.url
      link.target = '_blank'
      link.click()
    }
  } catch (error) {
    console.error('Error handling file download or open:', error)
  }
}

// 关闭预览窗口
const handleClosePreview = () => {
  previewVisible.value = false
  previewType.value = '' // 重置文件类型
}

// 预览图片
const handlePicturePreview = (url: string) => {
  // previewImageList.value = fileList.value.map((item) => item.url) // 生成所有图片的 URL 数组
  // previewIndex.value = previewImageList.value.indexOf(url) // 找到当前图片的索引
  // showViewer.value = true // 显示预览组件
}
</script>

<template>
  <el-card shadow="always">
    <div @click="togglePanel" class="header cursor-pointer">
      <span>基本信息</span>
      <el-icon v-if="isExpanded">
        <el-icon-arrow-down />
      </el-icon>
      <el-icon v-else>
        <el-icon-arrow-right />
      </el-icon>
    </div>
    <el-collapse-transition>
      <div v-show="isExpanded" v-if="!isLoading" class="w-full flex justify-between">
        <div class="w-100%">
          <el-descriptions
            title="基础信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('customer.cusname')">
              {{ currentRow?.cusname }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.phone')">
              {{ currentRow?.phone }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.email')">
              {{ currentRow?.email }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.status')">
              {{ useEnumeratePicker(statusOption, currentRow?.status ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.stage')">
              {{ useEnumeratePicker(stageOption, currentRow?.stage ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.loss')">
              {{ currentRow?.loss }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.role')">
              {{ currentRow?.role === 'distributor' ? '经销商' : '普通用户' }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.owner')">
              {{ useEnumeratePicker(operatorOptions, currentRow?.owner ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.partner')">
              {{ formatPartnerStr(currentRow?.partner ?? '') }}
            </el-descriptions-item>
          </el-descriptions>
          <el-divider border-style="dashed" />
          <el-descriptions
            title="扩展信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('customer.custype')">
              {{ useEnumeratePicker(custypeOption, currentRow?.custype ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.cusnature')">
              {{ useEnumeratePicker(cusnatureOption, currentRow?.cusnature ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.source')">
              {{ useEnumeratePicker(sourceOption, currentRow?.source ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.tags')">
              {{ currentRow?.tags }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.country')">
              {{ currentRow?.country }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.att_path')">
              <div>
                <div class="box-card" v-for="(file, index) in attachList" :key="index">
                  <div class="clearfix">
                    <span>{{ file.name }}</span
                    >&nbsp;&nbsp;&nbsp;&nbsp;
                    <el-button @click="handleFileClick(file)" type="text">预览</el-button>
                    <el-button @click="handleFileDownload(file)" type="text">下载</el-button>
                  </div>
                </div>
                <div v-if="!attachList || attachList.length === 0" class="no-files"> 暂无附件 </div>

                <!-- 使用Element Plus的Dialog组件来显示预览 -->
                <el-dialog
                  v-model="previewVisible"
                  :title="previewTitle"
                  width="80%"
                  height="92%"
                  :before-close="handleClosePreview"
                >
                  <!-- 根据文件类型显示预览内容 -->
                  <div v-if="previewType === 'image'">
                    <img :src="dialogFile?.url" alt="预览图片" class="w-80% ml-10%" />
                  </div>
                  <div v-if="previewType === 'pdf'">
                    <iframe
                      :src="dialogFile?.url"
                      style="width: 100%; height: 80vh"
                      frameborder="0"
                    ></iframe>
                  </div>
                  <div v-if="previewType === 'text'">
                    <iframe
                      :src="dialogFile?.url"
                      style="width: 100%; height: 80vh"
                      frameborder="0"
                    ></iframe>
                  </div>
                  <div v-if="previewType === 'other'">
                    <p>无法预览此文件，您可以下载它。</p>
                  </div>
                </el-dialog>
              </div>
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.remark')">
              {{ currentRow?.remark }}
            </el-descriptions-item>
          </el-descriptions>
          <el-divider border-style="dashed" />
          <el-descriptions
            title="系统信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('customer.is_login')">
              {{ useEnumeratePicker(isLoginOption, currentRow?.is_login ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.login_status')">
              {{ useEnumeratePicker(loginStatusOption, currentRow?.login_status ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.login_num')">
              {{ currentRow?.login_num }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.last_login_time')">
              {{ currentRow?.last_login_time }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.last_ip')">
              {{ currentRow?.last_ip }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.creator')">
              {{ useEnumeratePicker(operatorOptions, currentRow?.creator ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.create_time')">
              {{ currentRow?.create_time }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.update_time')">
              {{ currentRow?.update_time }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.last_followtime')">
              {{ currentRow?.last_followtime }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('customer.is_advance')">
              {{ currentRow?.is_advance === '1' ? '是' : '否' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-collapse-transition>
  </el-card>
</template>

<style scoped>
.header {
  display: flex;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 10px;
  font-weight: 900;
  background-color: #f3f3f3;
  border-radius: 5px;
  align-items: center;
  justify-content: space-between;
}

:deep(.is-bordered-label) {
  width: 200px;
}

/* 隐藏上传按钮 */

/* 隐藏 el-upload 的文本模式按钮 */
.only-preview :deep(.el-upload--picture-card) {
  display: none !important;
}

/* 也隐藏 el-upload--picture-card 的上传按钮 */
.only-preview :deep(.el-upload--picture-card) {
  display: none !important;
}

/* 文件列表样式 */

/* .box-card {
  margin-bottom: 8px;
}

.clearfix {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.clearfix span {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.no-files {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px;
} */
</style>
